<template>
  <view class="order-container">
    <!-- 订单状态筛选 -->
    <view class="order-filter">
      <text 
        class="filter-item" 
        :class="{ active: statusFilter === 'all' }"
        @click="statusFilter = 'all'"
      >全部</text>
      <text 
        class="filter-item" 
        :class="{ active: statusFilter === 'pending' }"
        @click="statusFilter = 'pending'"
      >待付款</text>
      <text 
        class="filter-item" 
        :class="{ active: statusFilter === 'delivering' }"
        @click="statusFilter = 'delivering'"
      >配送中</text>
      <text 
        class="filter-item" 
        :class="{ active: statusFilter === 'completed' }"
        @click="statusFilter = 'completed'"
      >已完成</text>
      <text 
        class="filter-item" 
        :class="{ active: statusFilter === 'cancelled' }"
        @click="statusFilter = 'cancelled'"
      >已取消</text>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view v-for="(order, index) in filteredOrders" :key="index" class="order-item">
        <!-- 店铺信息 -->
        <view class="store-info">
          <image class="store-icon" :src="getStoreImage(order.storeId)"></image>
          <text class="store-name">{{ getStoreName(order.storeId) }}</text>
          <text class="order-status">{{ getStatusText(order.status) }}</text>
          <text class="order-time">{{ formatOrderTime(order.orderTime) }}</text>
        </view>

        <!-- 商品列表 -->
        <view class="product-list">
          <view v-for="(product, pIndex) in order.products" :key="pIndex" class="product-item">
            <image class="product-image" :src="product.imgUrl"></image>
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <text class="product-price">¥{{ product.price }}</text>
              <text class="product-quantity">x{{ product.quantity }}</text>
            </view>
          </view>
        </view>

        <!-- 订单总价和操作 -->
        <view class="order-footer">
          <text class="total-price">共{{ getTotalQuantity(order.products) }}件 合计:¥{{ order.totalPrice }}</text>
          <view class="order-actions">
            <text v-if="order.status === 'delivering'" class="action-btn confirm-btn" @click="confirmReceipt(order.id)">确认收货</text>
            <text v-if="order.status === 'pending'" class="action-btn cancel-btn" @click="cancelOrder(order.id)">取消订单</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from "@/config.js";

export default {
  data() {
    return {
      orders: [], // 订单数据
      stores: [], // 店铺数据
      statusFilter: 'all' // 当前筛选状态
    };
  },

  computed: {
    filteredOrders() {
      if (this.statusFilter === 'all') {
        return this.orders;
      }
      return this.orders.filter(order => {
        if (this.statusFilter === 'pending') {
          return order.status === 'pending';
        } else if (this.statusFilter === 'delivering') {
          return order.status === 'delivering';
        } else if (this.statusFilter === 'completed') {
          return order.status === 'completed';
        } else if (this.statusFilter === 'cancelled') {
          return order.status === 'cancelled';
        }
        return false;
      });
    }
  },

  onLoad() {
    this.fetchOrders();
    this.fetchStores();
  },
  onShow() {
    // 重新获取订单数据
    this.fetchOrders();
    // 重新获取店铺数据（如果店铺数据可能有变化）
    this.fetchStores();
  },
  methods: {
    // 从后端获取订单数据
    fetchOrders() {
      uni.request({
        url: `${config.api_host}dingdan`,
        success: (res) => {
          // 为每个订单设置状态为"已付款"
          this.orders = res.data.map(order => ({
            ...order,
            status: 'paid' // 默认设置为已付款状态
          }));
        },
        fail: (error) => {
          console.error('获取订单数据失败:', error);
          uni.showToast({
            title: '加载订单失败',
            icon: 'none'
          });
        }
      });
    },

    // 从后端获取店铺数据
    fetchStores() {
      uni.request({
        url: `${config.api_host}super`,
        success: (res) => {
          this.stores = res.data;
        },
        fail: (error) => {
          console.error('获取店铺数据失败:', error);
        }
      });
    },

    // 根据店铺ID获取店铺名称
    getStoreName(storeId) {
      const store = this.stores.find(s => s._id === storeId);
      return store? store.name : '未知店铺';
    },

    // 根据店铺ID获取店铺图标
    getStoreImage(storeId) {
      const store = this.stores.find(s => s._id === storeId);
      return store? store.imgUrl : '/static/default-store.png';
    },

    // 计算商品总数量
    getTotalQuantity(products) {
      return products.reduce((total, product) => total + product.quantity, 0);
    },

    // 确认收货
    confirmReceipt(orderId) {
      uni.showModal({
        title: '确认收货',
        content: '确认收到商品了吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用 API 更新订单状态
            uni.request({
              url: `${config.api_host}dingdan/${orderId}`,
              method: 'PUT',
              data: {
                status: 'completed'
              },
              success: (res) => {
                if (res.statusCode === 200) {
                  // 更新前端订单状态
                  this.updateOrderStatus(orderId, 'completed');
                  uni.showToast({
                    title: '确认收货成功',
                    icon: 'success'
                  });
                } else {
                  uni.showToast({
                    title: '确认收货失败',
                    icon: 'none'
                  });
                }
              },
              fail: (error) => {
                console.error('更新订单状态失败:', error);
                uni.showToast({
                  title: '确认收货失败',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },

    // 取消订单
    cancelOrder(orderId) {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消此订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用 API 更新订单状态
            uni.request({
              url: `${config.api_host}dingdan/${orderId}`,
              method: 'PUT',
              data: {
                status: 'cancelled'
              },
              success: (res) => {
                if (res.statusCode === 200) {
                  // 更新前端订单状态
                  this.updateOrderStatus(orderId, 'cancelled');
                  uni.showToast({
                    title: '订单已取消',
                    icon: 'success'
                  });
                } else {
                  uni.showToast({
                    title: '取消订单失败',
                    icon: 'none'
                  });
                }
              },
              fail: (error) => {
                console.error('更新订单状态失败:', error);
                uni.showToast({
                  title: '取消订单失败',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    },

    // 更新订单状态
    updateOrderStatus(orderId, status) {
      this.orders = this.orders.map(order => {
        if (order.id === orderId) {
          return { ...order, status };
        }
        return order;
      });
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'pending': '待付款',
        'paid': '已付款', // 新增已付款状态
        'delivering': '配送中',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || '未知状态';
    },

    // 格式化订单时间
    formatOrderTime(orderTime) {
      const date = new Date(orderTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    }
  }
};
</script>    

<style scoped>
.order-container {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 订单筛选 */
.order-filter {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
  background-color: #fff;
  padding: 10px 0;
  border-radius: 8px;
}

.filter-item {
  font-size: 14px;
  color: #666;
  padding: 5px 10px;
}

.filter-item.active {
  color: #ff6700;
  font-weight: bold;
  border-bottom: 2px solid #ff6700;
}

/* 订单列表 */
.order-list {
  margin-bottom: 60px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

/* 店铺信息 */
.store-info {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 10px;
}

.store-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.store-name {
  font-size: 15px;
  font-weight: bold;
  flex: 1;
}

.order-status {
  font-size: 14px;
  color: #ff6700;
}

.order-time {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

/* 商品列表 */
.product-list {
  margin-bottom: 10px;
}

.product-item {
  display: flex;
  margin-bottom: 10px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 10px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 14px;
  color: #333;
}

.product-price {
  font-size: 15px;
  color: #ff6700;
  font-weight: bold;
}

.product-quantity {
  font-size: 13px;
  color: #999;
  align-self: flex-end;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.total-price {
  font-size: 14px;
  color: #666;
}

.order-actions {
  display: flex;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 13px;
  margin-left: 10px;
}

.confirm-btn {
  border: 1px solid #ff6700;
  color: #ff6700;
}

.cancel-btn {
  border: 1px solid #999;
  color: #666;
}
</style>    